from pydantic import BaseModel,ValidationError
from datetime import datetime
from typing import Optional,List
from pathlib import Path

def print_color(text):
    print(f"\033[31m===== {text} =====\033[0m")

class User(BaseModel):
    id : int                    #必填字段
    name : str = '小明'         #有默认值 选填字段
    register_time : datetime
    salary : float
    friends : List[int] = []   #列表中元素为int 或可以转换为int 的数据


request_data ={
    "id": 2001,
    "name": "jack",
    "register_time" : "2021-07-01 12:30:30",
    "salary": 20000,
    "friends" : [1001,'3001',4002]    #这里有字符串数字，也可以转换
}

user = User(**request_data)
print(user)

request_data ={
    "id": 'DDD',
    "name": "jack",
    "register_time" : "2021-07-01 12:30:30",
    "salary": 20000,
    "friends" : [1001,'AAA',4002]    #这里有字符串数字，也可以转换
}
try:
    user = User(**request_data)
    print(user)
except ValidationError as e:
    print(e.json())

user = User(id=43433,register_time=datetime.today(),salary=99999)
print(user)

# 一些常用的方法
print(user.dict())  #转dict
print(user.json())  #转json
print(user.copy())  #浅拷贝
try:
    # 和解构赋值功效一样
    print(User.parse_obj(request_data))
except:
    pass
#直接通过符合格式的字符串解析
print(User.parse_raw('{"id": 66666, "name": "\u5c0f\u660e", "register_time": "2021-05-21T10:23:06.014212", "salary": 99999.0, "friends": []}'))

#print('{"id": 33445566, "name": "阿萨的", "register_time": "2021-05-21T10:23:06.014212", "salary": 99999.0, "friends": []}'.encode("utf-8"))
path = Path('user.json')
path.write_text('{"id": 33445566, "name": "阿萨的", "register_time": "2021-05-21T10:23:06.014212", "salary": 99999.0, "friends": []}',encoding='utf-8')
print(User.parse_file(path))